import React from 'react';
import Child from './Child'
import store from '../../store/index'
import indexStyle from '../todo/index.module.css'
import {INPUT_CHANGE, ADD_ITEM, DELETE_ITEM, GET_LIST} from '../../store/actionTypes'
import {getTodoList} from '../../store/actionCreator'

class ReduxTest extends React.Component{
    constructor(props){
        super(props)
        //console.log(props)
        this.state = {
            userName: 'Mike'
        }
        this.state = Object.assign(this.state, store.getState())
        //通过订阅的方式实现store数据修改同步渲染到UI界面
        store.subscribe(this.storeChange)
    }
    componentDidMount(){
		//1.直接请求
        this.curretComponentGetTodoList()
        //console.log(store.getState())
		
		//2.使用redux-chunk返回一个函数作为action
		/* let action = getTodoList()
		console.log(action)
		store.dispatch(action) */
    }
    curretComponentGetTodoList () {
        fetch('https://www.fastmock.site/mock/29ebf623e2c8f366218993cdf6b1f640/testapi/getTodoList').then(res => {
			if(res.ok){
				console.log(res)//返回的原始数据流
				//console.log(res.json())//json格式化的数据返回promise对象在then回调中接收
				res.json().then(result => {
					console.log(result)
					let action = {
						type: GET_LIST,
						data: [],
					}
					if(result.code === '0000'){
						action.data = result.data
					}
					store.dispatch(action)
				})
			}
		}).catch(err => console.log(err))

    }
    handleChange = (e) => {
        let action = {
            type: INPUT_CHANGE,
            value: e.target.value
        }
        store.dispatch(action)
    }
    handleAddClick = () => {
        if(!this.state.defaultValue){
            return
        }
        let action = {
            type: ADD_ITEM,
        }
        store.dispatch(action)
    }
    handleDetele = (index) => {
        let action = {
            type: DELETE_ITEM,
            index
        }
        store.dispatch(action)
    }
    storeChange = () => {
        this.setState(store.getState())
    }
    
    render(){
        return (
            <div>
                <h3 className={indexStyle.title}>ReduxTest组件：学习Redux的相关示例</h3>
                {this.state.userName}
                <input type="text" value={this.state.defaultValue} onChange={this.handleChange} />
                <button type="button" onClick={()=>{this.handleAddClick()}}>点击增加数据</button>
                {
                    this.state.dataList.map((element, index) => {
                        return (
                            <div key={index}>
                                <p>name:{element.name}-age:{element.age}-index:{index}</p>
                                <span style={{'float': 'right'}} onClick={()=>{this.handleDetele(index)}}>X</span>
                            </div>
                        )
                    })
                }
                <Child  dataList={this.state.dataList}></Child>
            </div>
        )
    }

}

export default ReduxTest
